package com.kkarma.service.impl;

import com.kkarma.exception.LoginException;
import com.kkarma.service.LoginService;
import com.kkarma.util.service.TokenService;
import com.kkarma.vo.LoginBody;
import com.kkarma.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;



/**
 * @Author: karma
 * @Date: 2022/3/30 0030 - 03 - 30 - 12:50
 * @Description: com.kkarma.service.impl
 * @version: 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    private final TokenService tokenService;

    private final AuthenticationManager authenticationManager;

    @Autowired
    public LoginServiceImpl(TokenService tokenService, AuthenticationManager authenticationManager) {
        this.tokenService = tokenService;
        this.authenticationManager = authenticationManager;
    }


    @Override
    public String login(LoginBody loginBody) {
        // 调用spring security的验证逻辑进行账号密码的验证
        Authentication authentication = null;
        try{
            authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword()));
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.createToken(loginUser);
    }
}
